package com.jeomo.shiro.bean;

import com.jeomo.shiro.dto.LoginInfo;
import com.jeomo.sys.api.bo.PermissionBo;
import com.jeomo.sys.api.bo.RoleBo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author: qbt
 * @Date: 2020/7/26 22:06
 * @Version 1.0
 */
public abstract class ShiroBaseUserRealm extends AuthorizingRealm {

    public Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 执行授权逻辑
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        LoginInfo loginInfo = (LoginInfo) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
        Set<String> permissionCodes = new HashSet<>();
        if(loginInfo.getLoginUser().getRoles() != null) {
            for (RoleBo role : loginInfo.getLoginUser().getRoles()) {
                info.addRole(role.getCode());
                List<PermissionBo> permissions = role.getPermissions();
                if(permissions != null) {
                    for(PermissionBo permission : role.getPermissions()) {
                        permissionCodes.add(permission.getCode());
                    }

                }
            }
        }
        for(String permission : permissionCodes) {
            info.addStringPermission(permission);
        }
        return info;
    }

    /**
     * 获取加密方法
     * @return
     */
    @Bean
    @Override
    public CredentialsMatcher getCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1024);
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }


}
